package com.asiainfo.iam.tool;


import com.alibaba.fastjson.JSON;
import com.asiainfo.iam.entity.vo.MessageBase;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 计算消息体的hash值，用于存入布隆过滤器
 */
@Component
public class MsgDigesUtil {
    /**
     * 计算消息体的SHA-256哈希值
     */
    public static String calculateHash(String messageBody){
        try {
            MessageBase<?> baseMsg = JSON.parseObject(messageBody, MessageBase.class);//解析消息体
            String data = JSON.toJSONString(baseMsg.getMsgData());//获取消息体数据
            MessageDigest digest = MessageDigest.getInstance("SHA-256");// 创建一个SHA-256消息摘要对象
            byte[] hashBytes = digest.digest(data.getBytes());// 计算消息体的哈希值

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes){
                String hex = String.format("%02x", b);// 将字节转换为十六进制字符串
                hexString.append(hex);// 将十六进制字符串添加到结果中
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("计算消息哈希失败",e);
        }
    }

}
